package com.rom.array;

/**
 * 稀疏数组
 */
public class sparseArray {
    public static void main(String[] args) {
        //0 表示没有棋子，1表示黑、2表示蓝
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[3][4] = 1;
        int sum = 0;

        for (int[] row:chessArr1) {
            for(int data :row){
                if(data != 0){
                    sum++;
                }
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }


        int[][] spareseArr = new int[sum+1][3];
//        稀疏数组赋值首行
        spareseArr[0][0] = 11;
        spareseArr[0][1] = 11;
        spareseArr[0][2] = sum;
        int count = 1;
        //将数组非0值传入
        for (int i = 0; i < chessArr1.length; i++) {
            for (int j = 0; j < chessArr1.length; j++) {
                if(chessArr1[i][j]!=0){
                    //存入稀疏数组
                    spareseArr[count][0] = i;
                    spareseArr[count][1] = j;
                    spareseArr[count][2] = chessArr1[i][j];
                    count++;
                }
            }
        }
        //转化稀疏数组
        System.out.println("转化稀疏数组");
        for (int[] row : spareseArr) {
            for (int data:row) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        //
        System.out.println("转化数组");
        int[][] chessArr2 = new int[spareseArr[0][0]][spareseArr[0][1]];
        for (int i = 1; i < spareseArr.length; i++) {
            chessArr2[spareseArr[i][0]][spareseArr[i][1]] = spareseArr[i][2];
        }
        for (int[] row: chessArr2) {
            for (int data : row) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

    }
}
